<template>
  <div class="message-input">
    <div class="input-container">
      <!-- 文件上传按钮 -->
      <button 
        class="attachment-btn" 
        @click="handleAttachmentClick"
        :disabled="disabled"
        title="发送文件"
      >
        <i class="icon-attachment"></i>
      </button>

      <!-- 文本输入区域 -->
      <div class="input-wrapper">
        <textarea
          ref="textareaRef"
          v-model="inputText"
          :placeholder="placeholder"
          :disabled="disabled"
          class="message-textarea"
          @keydown="handleKeyDown"
          @input="handleInput"
          @paste="handlePaste"
          rows="1"
        ></textarea>
        
        <!-- 字符计数 -->
        <div v-if="showCharCount" class="char-count" :class="{ 'over-limit': isOverLimit }">
          {{ inputText.length }}/{{ maxLength }}
        </div>
      </div>

      <!-- 发送按钮 -->
      <button 
        class="send-btn" 
        @click="handleSend"
        :disabled="!canSend"
        :class="{ 'sending': sending }"
        title="发送消息"
      >
        <i v-if="sending" class="icon-loading spinning"></i>
        <i v-else class="icon-send"></i>
      </button>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      <i class="icon-error"></i>
      <span>{{ error }}</span>
      <button @click="clearError" class="error-close">×</button>
    </div>

    <!-- 正在输入指示器（给其他用户看的） -->
    <div v-if="isTyping" class="typing-status">
      正在输入...
    </div>

    <!-- 文件上传隐藏input -->
    <input
      ref="fileInputRef"
      type="file"
      multiple
      accept="image/*,.pdf,.doc,.docx,.txt"
      @change="handleFileSelect"
      style="display: none"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { useChatStore } from '@/stores/chat'
import { validateMessage, debounce } from '@/utils'

interface Props {
  placeholder?: string
  disabled?: boolean
  maxLength?: number
  showCharCount?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '输入消息...',
  disabled: false,
  maxLength: 5000,
  showCharCount: false
})

const emit = defineEmits<{
  send: [content: string, type?: 'text' | 'image' | 'file']
  typing: [isTyping: boolean]
  focus: []
  blur: []
}>()

const chatStore = useChatStore()
const textareaRef = ref<HTMLTextAreaElement>()
const fileInputRef = ref<HTMLInputElement>()
const inputText = ref('')
const sending = ref(false)
const error = ref('')
const isTyping = ref(false)

// 计算属性
const canSend = computed(() => {
  return !props.disabled && 
         !sending.value && 
         inputText.value.trim().length > 0 && 
         !isOverLimit.value
})

const isOverLimit = computed(() => {
  return inputText.value.length > props.maxLength
})

// 防抖的输入处理
const debouncedTyping = debounce((typing: boolean) => {
  isTyping.value = typing
  emit('typing', typing)
}, 300)

// 方法
const handleInput = () => {
  adjustTextareaHeight()
  
  if (inputText.value.trim().length > 0) {
    debouncedTyping(true)
  } else {
    debouncedTyping(false)
  }
}

const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    if (event.shiftKey) {
      // Shift+Enter 换行，不做任何处理，让默认行为发生
      return
    } else {
      // Enter 发送消息
      event.preventDefault()
      handleSend()
    }
  }
}

const handleSend = async () => {
  if (!canSend.value) return

  const content = inputText.value.trim()
  if (!validateMessage(content)) {
    setError('消息内容无效')
    return
  }

  try {
    sending.value = true
    clearError()
    
    // 发送消息
    emit('send', content, 'text')
    
    // 清空输入框
    inputText.value = ''
    isTyping.value = false
    emit('typing', false)
    
    // 重置textarea高度
    adjustTextareaHeight()
    
    // 聚焦输入框
    focusInput()
    
  } catch (err) {
    const errorMessage = err instanceof Error ? err.message : '发送失败'
    setError(errorMessage)
  } finally {
    sending.value = false
  }
}

const handleAttachmentClick = () => {
  if (props.disabled) return
  fileInputRef.value?.click()
}

const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files
  
  if (!files || files.length === 0) return

  // TODO: 实现文件上传逻辑
  console.log('Selected files:', files)
  
  // 重置文件输入
  target.value = ''
}

const handlePaste = (event: ClipboardEvent) => {
  const items = event.clipboardData?.items
  if (!items) return

  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    
    if (item.type.indexOf('image') !== -1) {
      event.preventDefault()
      const file = item.getAsFile()
      if (file) {
        // TODO: 处理粘贴的图片
        console.log('Pasted image:', file)
      }
    }
  }
}

const adjustTextareaHeight = () => {
  nextTick(() => {
    if (textareaRef.value) {
      textareaRef.value.style.height = 'auto'
      const scrollHeight = textareaRef.value.scrollHeight
      const maxHeight = 120 // 最大高度约6行
      textareaRef.value.style.height = Math.min(scrollHeight, maxHeight) + 'px'
    }
  })
}

const focusInput = () => {
  nextTick(() => {
    textareaRef.value?.focus()
    emit('focus')
  })
}

const blurInput = () => {
  textareaRef.value?.blur()
  emit('blur')
}

const setError = (message: string) => {
  error.value = message
  setTimeout(() => {
    if (error.value === message) {
      clearError()
    }
  }, 5000)
}

const clearError = () => {
  error.value = ''
}

const insertText = (text: string) => {
  if (!textareaRef.value) return
  
  const textarea = textareaRef.value
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  
  inputText.value = inputText.value.substring(0, start) + text + inputText.value.substring(end)
  
  nextTick(() => {
    textarea.selectionStart = textarea.selectionEnd = start + text.length
    textarea.focus()
    adjustTextareaHeight()
  })
}

// 监听活跃聊天变化，清空输入框
watch(() => chatStore.activeChat, () => {
  inputText.value = ''
  isTyping.value = false
  clearError()
  adjustTextareaHeight()
})

// 组件挂载时聚焦
onMounted(() => {
  focusInput()
})

// 组件卸载时清理
onUnmounted(() => {
  debouncedTyping(false)
})

// 暴露方法给父组件
defineExpose({
  focusInput,
  blurInput,
  insertText,
  clearInput: () => {
    inputText.value = ''
    adjustTextareaHeight()
  }
})
</script>

<style scoped>
.message-input {
  padding: 16px;
  background: var(--color-background);
  border-top: 1px solid var(--color-border);
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: 8px;
  padding: 8px;
  transition: border-color 0.2s;
}

.input-container:focus-within {
  border-color: var(--color-primary);
}

.attachment-btn {
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  color: var(--color-text-secondary);
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.attachment-btn:hover:not(:disabled) {
  background: var(--color-hover);
  color: var(--color-primary);
}

.attachment-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.input-wrapper {
  flex: 1;
  position: relative;
}

.message-textarea {
  width: 100%;
  border: none;
  outline: none;
  background: transparent;
  color: var(--color-text);
  font-size: 14px;
  line-height: 1.4;
  resize: none;
  min-height: 20px;
  max-height: 120px;
  font-family: inherit;
}

.message-textarea::placeholder {
  color: var(--color-text-secondary);
}

.char-count {
  position: absolute;
  bottom: -20px;
  right: 0;
  font-size: 11px;
  color: var(--color-text-secondary);
}

.char-count.over-limit {
  color: var(--color-error);
}

.send-btn {
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  border: none;
  background: var(--color-primary);
  color: white;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.send-btn:hover:not(:disabled) {
  background: var(--color-primary-dark);
  transform: translateY(-1px);
}

.send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.send-btn.sending {
  background: var(--color-primary-light);
}

.error-message {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  padding: 8px 12px;
  background: rgba(var(--color-error-rgb), 0.1);
  border: 1px solid var(--color-error);
  border-radius: 4px;
  color: var(--color-error);
  font-size: 12px;
}

.error-close {
  margin-left: auto;
  background: none;
  border: none;
  color: var(--color-error);
  cursor: pointer;
  font-size: 16px;
  line-height: 1;
  padding: 0;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.typing-status {
  margin-top: 4px;
  font-size: 11px;
  color: var(--color-text-secondary);
  font-style: italic;
}

.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 图标样式 */
.icon-attachment::before { content: '📎'; }
.icon-send::before { content: '➤'; }
.icon-loading::before { content: '⟳'; }
.icon-error::before { content: '⚠'; }

/* 响应式设计 */
@media (max-width: 768px) {
  .message-input {
    padding: 12px;
  }
  
  .input-container {
    padding: 6px;
  }
  
  .attachment-btn,
  .send-btn {
    width: 28px;
    height: 28px;
  }
}
</style>